package com.qf.fcy.youshare.task;

import android.os.AsyncTask;
import android.util.Log;
import com.qf.fcy.youshare.Constants;
import com.qf.fcy.youshare.utils.HttpClientHelper;
import com.qf.fcy.youshare.utils.TaskProcessor;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;

/**
 * Created with IntelliJ IDEA.
 * User: Alex[FR]
 * Date: 2015/2/5
 * Email: alex_fcy@163.com
 */

/**
 * 获取产品列表接口调用，这个异步任务在 核心产品与平台产品中都使用到了
 */

/*
 * 对于异步任务，通常定义最长的参数集合，然后利用参数数组的长度，检查、
 */
public class ProductListTask extends AsyncTask<String, Integer, JSONObject> {
    private TaskProcessor processor;

    public ProductListTask(TaskProcessor processor) {
        this.processor = processor;
    }

    @Override
    protected JSONObject doInBackground(String... params) {
        JSONObject ret = null;

        if (params != null && params.length > 0) {
            // 产品列表接口支持指定分类ID，用于获取指定分类下的产品列表
            String id = params[0];
            // 默认值
            String size = "5";
            String page = "1";
            switch (params.length) {
                case 2:
                    size = params[1];
                    break;
                case 3:
                    size = params[1];
                    page = params[2];
                    break;
            }
            // GET 请求 参数 采用 key=value&key=value
            String url = Constants.API_POINT + "/category.php?id=" + id
                    + "&size=" + size
                    + "&page" + page; // 获取产品分类商品列表的接口
            byte[] bytes = HttpClientHelper.get(url);
            if (bytes != null) {
                try {
                    String str = new String(bytes, "UTF-8");
                    ret = new JSONObject(str);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }

        return ret;
    }

    @Override
    protected void onPostExecute(JSONObject result) {
        if (result != null) {
            processor.processor(result);
        }
    }
}
